package study.仪器解析.串口化通信.生化仪.打包;

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import study.仪器解析.串口化通信.生化仪.ASTMParser;

/**
 * @Author 刘伟涛
 * @Date 2024/8/7 15:03
 **/
public class SerialPortReader {
    private SerialPort serialPort;

    public SerialPortReader(String portName) {
        serialPort = new SerialPort(portName);
    }

    public void initialize() {
        try {
            // 打开串口
            serialPort.openPort();

            // 设置串口参数
            serialPort.setParams(
                    SerialPort.BAUDRATE_9600,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE
            );

            // 设置事件监听器，监听串口数据到达事件
            serialPort.addEventListener(new SerialPortEventListener() {
                @Override
                public void serialEvent(SerialPortEvent event) {
                    if (event.isRXCHAR()) { // 检查是否有数据到达
                        try {
                            // 读取数据
                            String receivedData = serialPort.readString(event.getEventValue());
                            System.out.println("Received data: " + receivedData);

                            ASTMParser astmParser = new ASTMParser();
                            astmParser.parseASTMMessage(receivedData);

                        } catch (SerialPortException ex) {
                            System.out.println("Error in receiving data: " + ex);
                        }
                    }
                }
            });

        } catch (SerialPortException ex) {
            System.out.println("Error in initializing serial port: " + ex);
        }
    }

    public void close() {
        try {
            if (serialPort.isOpened()) {
                serialPort.closePort();
            }
        } catch (SerialPortException ex) {
            System.out.println("Error in closing serial port: " + ex);
        }
    }

    public static void main(String[] args) {
        SerialPortReader reader = new SerialPortReader("COM2");
        reader.initialize();

        // 添加一个简单的阻塞以便继续接收数据，通常使用线程管理
        try {
            Thread.sleep(10000000); // 运行10秒后停止
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        reader.close();
    }
}
